package tech.wetech.admin3.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tech.wetech.admin3.sys.model.AooAnotherMe;
import tech.wetech.admin3.sys.model.AooAnotherSomeone;
import tech.wetech.admin3.sys.model.AooVirtualMan;
import tech.wetech.admin3.sys.service.AooAnotherMeService;
import tech.wetech.admin3.sys.service.AooAnotherSomeoneService;
import tech.wetech.admin3.sys.service.AooPhoneCodeService;
import tech.wetech.admin3.sys.service.AooVirtualManService;
import tech.wetech.admin3.util.CustomResponse;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/mhv")
public class AooCountController {
  private AooAnotherMeService anotherMeService;
  private AooAnotherSomeoneService someoneService;
  private AooVirtualManService virtualManService;
  private AooPhoneCodeService phoneCodeService;

  public AooCountController(
    AooAnotherMeService anotherMeService,
    AooAnotherSomeoneService someoneService,
    AooVirtualManService virtualManService,
    AooPhoneCodeService phoneCodeService
  ) {
    this.anotherMeService = anotherMeService;
    this.someoneService = someoneService;
    this.virtualManService = virtualManService;
    this.phoneCodeService = phoneCodeService;
  }

  @GetMapping("/getmhv_bystatus")
  public ResponseEntity<?> getMhvByStatus(
    @RequestParam("status") Integer status,
    @RequestParam("paid") Boolean paid
  ) {
    List<Object> dataList = new ArrayList<>();
    List<?> data1 = anotherMeService.findByStatus(status);
    List<?> data2 = someoneService.findByAgreeOrNotAndStatus(1, status);  // 仅查询agreeOrNot：1
    List<?> data3 = virtualManService.findByStatus(status);
    dataList.addAll(data1);
    dataList.addAll(data2);
    dataList.addAll(data3);

    List<Object> filteredDataList = dataList.stream()
      .filter(data -> {
        // 检查对象是否有getPaid方法并调用它
        try {
          Method getPaidMethod = data.getClass().getMethod("isPaid");
          System.out.println("getPaidMethod.invoke(data): " + getPaidMethod.invoke(data));
          return getPaidMethod.invoke(data).equals(paid);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
          e.printStackTrace();
          return false;
        }
      })
      .collect(Collectors.toList());

    Map<String, Object> resulet = new HashMap<>();
    resulet.put("total", filteredDataList.size());
    resulet.put("record", filteredDataList);
    return ResponseEntity.ok(new CustomResponse.r1<>("ok", true, resulet));
  }

  @GetMapping("/getall_mhv")    // 查询所有虚拟人
  public ResponseEntity<?> getAllMHV(
    @RequestParam("page") int page,
    @RequestParam("size") int size,
    @RequestParam("type") String type,
    @RequestParam(value = "paid", required = false) Boolean paid
  ) {
    List<Object> combinedList = new ArrayList<>();
    List<AooAnotherMe> data1 = anotherMeService.getAllData();
    List<AooAnotherSomeone> data2 = someoneService.getAllDataAgree();
    List<AooVirtualMan> data3 = virtualManService.getAllData();
    // 重编合成表的id
    int idCounter = 1;
    for (AooAnotherMe record : data1) {
      record.setId(idCounter++);
    }
    for (AooAnotherSomeone record : data2) {
      record.setId(idCounter++);
    }
    for (AooVirtualMan record : data3) {
      record.setId(idCounter++);
    }
    combinedList.addAll(data1);
    combinedList.addAll(data2);
    combinedList.addAll(data3);

    List<Object> filteredList = new ArrayList<>();
    if ("zrr".equals(type)) {
      filteredList = combinedList.stream().filter(obj -> {
        if (obj instanceof AooAnotherMe) {
          return ((AooAnotherMe) obj).getType() != null && ((AooAnotherMe) obj).getType() == 1 && (paid == null || ((AooAnotherMe) obj).isPaid() == paid);
        } else if (obj instanceof AooAnotherSomeone) {
          return ((AooAnotherSomeone) obj).getType() != null && ((AooAnotherSomeone) obj).getType() == 2 && (paid == null || ((AooAnotherSomeone) obj).isPaid() == paid);
        }
        return false;
      }).toList();
    } else if ("xnr".equals(type)) {
      filteredList = combinedList.stream().filter(obj -> obj instanceof AooVirtualMan && ((AooVirtualMan) obj).getType() != null && ((AooVirtualMan) obj).getType() == 3 && (paid == null || ((AooVirtualMan) obj).isPaid() == paid)).toList();
    } else if ("all".equals(type)) {
      filteredList = combinedList.stream().filter(obj -> {
        if (obj instanceof AooAnotherMe) {
          return paid == null || ((AooAnotherMe) obj).isPaid() == paid;
        } else if (obj instanceof AooAnotherSomeone) {
          return paid == null || ((AooAnotherSomeone) obj).isPaid() == paid;
        } else if (obj instanceof AooVirtualMan) {
          return paid == null || ((AooVirtualMan) obj).isPaid() == paid;
        }
        return false;
      }).toList();
    } else {
      throw new IllegalArgumentException("type参数错误");
    }

    int total = filteredList.size();
    int start = page * size;
    int end = Math.min(start + size, filteredList.size());

    List<Object> paginatedList;

    if (start < total) {
      paginatedList = filteredList.subList(start, end);
    } else {
      paginatedList = new ArrayList<>();
    }

    Map<String, Object> result = new HashMap<>();
    result.put("page", page);
    result.put("size", size);
    result.put("total", total);
    result.put("record", paginatedList);

    return ResponseEntity.ok(new CustomResponse.r1<>("ok", true, result));
  }

  @GetMapping("/admin/getall_mhv")    // 查询所有虚拟人
  public ResponseEntity<?> adminGetAllMHV(
    @RequestParam("page") int page,
    @RequestParam("size") int size,
    @RequestParam("type") String type,
    @RequestParam(value = "paid", required = false) Boolean paid,
    @RequestParam("vericode") String vericode
  ) {
    boolean flag = phoneCodeService.admin_VerifyCode(vericode);
    if (!flag) {
      return ResponseEntity.ok(new CustomResponse.r1("admin 验证码错误或已过期", false, null));
    }
//
    List<Object> combinedList = new ArrayList<>();
    List<AooAnotherMe> data1 = anotherMeService.getAllData();
    List<AooAnotherSomeone> data2 = someoneService.getAllDataAgree();
    List<AooVirtualMan> data3 = virtualManService.getAllData();
    // 重编合成表的id
    int idCounter = 1;
    for (AooAnotherMe record : data1) {
      record.setId(idCounter++);
    }
    for (AooAnotherSomeone record : data2) {
      record.setId(idCounter++);
    }
    for (AooVirtualMan record : data3) {
      record.setId(idCounter++);
    }
    combinedList.addAll(data1);
    combinedList.addAll(data2);
    combinedList.addAll(data3);

    List<Object> filteredList = new ArrayList<>();
    if ("zrr".equals(type)) {
      filteredList = combinedList.stream().filter(obj -> {
        if (obj instanceof AooAnotherMe) {
          return ((AooAnotherMe) obj).getType() != null && ((AooAnotherMe) obj).getType() == 1 && (paid == null || ((AooAnotherMe) obj).isPaid() == paid);
        } else if (obj instanceof AooAnotherSomeone) {
          return ((AooAnotherSomeone) obj).getType() != null && ((AooAnotherSomeone) obj).getType() == 2 && (paid == null || ((AooAnotherSomeone) obj).isPaid() == paid);
        }
        return false;
      }).toList();
    } else if ("xnr".equals(type)) {
      filteredList = combinedList.stream().filter(obj -> obj instanceof AooVirtualMan && ((AooVirtualMan) obj).getType() != null && ((AooVirtualMan) obj).getType() == 3 && (paid == null || ((AooVirtualMan) obj).isPaid() == paid)).toList();
    } else if ("all".equals(type)) {
      filteredList = combinedList.stream().filter(obj -> {
        if (obj instanceof AooAnotherMe) {
          return paid == null || ((AooAnotherMe) obj).isPaid() == paid;
        } else if (obj instanceof AooAnotherSomeone) {
          return paid == null || ((AooAnotherSomeone) obj).isPaid() == paid;
        } else if (obj instanceof AooVirtualMan) {
          return paid == null || ((AooVirtualMan) obj).isPaid() == paid;
        }
        return false;
      }).toList();
    } else {
      throw new IllegalArgumentException("type参数错误");
    }

    int total = filteredList.size();
    int start = page * size;
    int end = Math.min(start + size, filteredList.size());

    List<Object> paginatedList;

    if (start < total) {
      paginatedList = filteredList.subList(start, end);
    } else {
      paginatedList = new ArrayList<>();
    }

    Map<String, Object> result = new HashMap<>();
    result.put("page", page);
    result.put("size", size);
    result.put("total", total);
    result.put("record", paginatedList);

    return ResponseEntity.ok(new CustomResponse.r1<>("ok", true, result));
  }


  @GetMapping("/get_by_digitalName")    // 名字查询
  public ResponseEntity<?> getByDigitalName(
    @RequestParam("digitalName") String digitalName,
    @RequestParam("paid") Boolean paid
  ) {
    List<?> data1 = anotherMeService.findByDigitalNameContaining(digitalName);
    List<?> data2 = someoneService.findByDigitalNameContaining(digitalName);    // agreeOrNot ??
    List<?> data3 = virtualManService.findByDigitalNameContaining(digitalName);
    List<Object> combinedList = new ArrayList<>();
    combinedList.addAll(data1);
    combinedList.addAll(data2);
    combinedList.addAll(data3);

    List<Object> filteredDataList = combinedList.stream()
      .filter(data -> {
        // 检查对象是否有getPaid方法并调用它
        try {
          Method getPaidMethod = data.getClass().getMethod("isPaid");
          System.out.println("getPaidMethod.invoke(data): " + getPaidMethod.invoke(data));
          return getPaidMethod.invoke(data).equals(paid);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
          e.printStackTrace();
          return false;
        }
      })
      .collect(Collectors.toList());

    return ResponseEntity.ok(new CustomResponse.r1<>("ok", true, filteredDataList));
  }


}
